//
//  AppDelegate.swift
//  Weibo
//
//  Created by 张婷 on 15/10/14.
//  Copyright © 2015年 itheima. All rights reserved.
//

import UIKit

@UIApplicationMain

class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?

    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
        
        setupApperence()
        
        window = UIWindow(frame: UIScreen.mainScreen().bounds)
        
        window?.backgroundColor = UIColor.whiteColor()
        
        window?.rootViewController = defaultRootViewController
        
        window?.makeKeyAndVisible()
        
        // 测试视图模型
        print(UserAccountViewModel.sharedUserAccountModel.userAccount)
        
        // 监听通知
        NSNotificationCenter.defaultCenter().addObserverForName(
            WBSwitchRootviewControllerNotification,           // 通知的名称
            object: nil,                                      // 发送通知的对象，如果为 nil 则可以监听所有对象
            queue: nil)                                       // Nil  主线程
            { [weak self](notification) -> Void in
                
                let vc = notification.object != nil ? WelcomeViewController() : MainViewController()
                
                // 切换控制器
                self?.window?.rootViewController = vc
        }
        
        return true
    }
    
    /// 注销通知
    deinit {
        NSNotificationCenter.defaultCenter().removeObserver(self, name: WBSwitchRootviewControllerNotification, object: nil)
    }
    
    private func setupApperence() {
        // 修改导航栏的全局外观 － 要在控件创建之前设置，一经设置全局有效
        UINavigationBar.appearance().tintColor = WBApperenceTintColor
        UITabBar.appearance().tintColor = WBApperenceTintColor
    }
}

// MARK: - 界面切换代码
extension AppDelegate {
    
    /// 设置默认的控制器
    private var defaultRootViewController: UIViewController {
        
        // 判断是否登录
        if UserAccountViewModel.sharedUserAccountModel.userLogon {
            return isNewVersion ? NewFeatureViewController() : WelcomeViewController()
        }
        return MainViewController()
    }
    
    /// 是不是新版本
    private var isNewVersion: Bool {
        // 获取当前版本号
        let currentVersion = NSBundle.mainBundle().infoDictionary!["CFBundleShortVersionString"] as! String
        // double 才能比较大小
        let version = Double(currentVersion)
        
        let sandboxVersionKey = "sandboxVersionKey"
        let sandboxVersion = NSUserDefaults.standardUserDefaults().doubleForKey(sandboxVersionKey)
        
        // 当前版本号保存到沙盒
        NSUserDefaults.standardUserDefaults().setDouble(version!, forKey: sandboxVersionKey)
        
        return version > sandboxVersion
    }
}

